<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>javascript 阶段</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: deepskyblue;
            margin-top: 10px;
        }

        .line {
            width: 1000px;
            height: 5px;
            background-color: #000;
            margin: 10px 0;
        }

        .btn-start {
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="line"></div>
    <button class="btn-start">改变宽度</button>
    <script>
        var animate = function (dom, prop, value, cailback) {
            clearInterval(dom.timer);
            dom.timer = setInterval(function () {
                var target = parseInt(value);
                var cur = parseInt(getComputedStyle(dom)[prop]);
                var speed = (target - cur) / 10;
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

                if (cur == target) {
                    console.log("当前属性值：" + cur);
                    clearInterval(dom.timer);
                    if (typeof cailback == "function") {
                        cailback();
                    }
                    return;
                }
                dom.style[prop] = cur + speed + "px";
            }, 10)
        }

        var box = document.querySelector(".box");
        var btn = document.querySelector(".btn-start");

        btn.onclick = function () {
            // 调用动画函数
            // animate(box,"height","200px");
            // animate(box,"marginLeft","500px");// 当前等于 199 , 200,  201  ; 步长 0.3 
            animate(box, "marginLeft", "500px", function () {
                // 当box移动到500px位置 设置box为背景色绿色
                // box.style["background"] = "green";
                var r=Math.floor(Math.random()*256);
                var g=Math.floor(Math.random()*256);
                var b=Math.floor(Math.random()*256);
                box.style["background"] = "rgb("+r+","+g+","+b+")";
            });
        }

        // function randomColor1()
        //     {
        //         var r=Math.floor(Math.random()*256);
        //         var g=Math.floor(Math.random()*256);
        //         var b=Math.floor(Math.random()*256);
        //         //在控制器中显示出随机生成的颜色(可以删除,无影响)
        //         console.log("rgb("+r+","+g+","+b+")");
        //         //返回随机生成的颜色
        //         return "rgb("+r+","+g+","+b+")";
        //     }
    </script>
</body>

</html>